package org.apache.ocean.main.search;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;

import org.apache.ocean.main.Snapshot;
import org.apache.ocean.main.Index.IndexSnapshot;
import org.apache.ocean.main.search.Search.Aggregate;
import org.apache.ocean.main.search.cache.FieldCacheKey.ValueIndexCursor;
import org.apache.ocean.main.util.Range;

public class AggregateSearch implements Callable<Object> {
	private final Aggregate aggregate;
	private final Snapshot snapshot;
	
  public AggregateSearch(Aggregate aggregate, Snapshot snapshot) {
  	this.aggregate = aggregate;
  	this.snapshot = snapshot;
  }
  
  public Object call() throws Exception {
  	Collection<IndexSnapshot> indexSnapshots = snapshot.getIndexSnapshots();
  	List list = new ArrayList(indexSnapshots.size());
  	for (IndexSnapshot indexSnapshot : indexSnapshots) {
  		String field = aggregate.getField();
  		Range range = aggregate.getRange();
  		ValueIndexCursor valueIndexCursor = indexSnapshot.getValueIndexCursor(field, range);
  		Object value = null;
  		if (aggregate.getType().equals(Aggregate.MIN)) {
  			value = valueIndexCursor.firstKey();
  		} else if (aggregate.getType().equals(Aggregate.MAX)) {
  			value = valueIndexCursor.lastKey();
  		}
  		if (value != null) list.add(value);
  	}
  	return Collections.max(list);
  }
}
